import { IDomEditor, IEditorConfig } from '@wangeditor/editor';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { useEffect, useRef, useState } from 'react';
import { util } from '../../functionalComponent/table/util';
import { iup, registerComponent } from '../../util';
import { richUploadFile } from '../Attachment/service';
import { getFileMd5 } from '../Attachment/util';
import { ImageElement, InsertFnType, toolbarConfig } from './type';

const splitKey = '__jkd__';

export function HtmlEditor(props: {
  value: string;
  fileTypeCode: string;
  editorProps: any;
  onChange: (value: any) => void;
}) {
  const { value, fileTypeCode, editorProps, onChange } = props;
  const cursorIdRef = useRef(0);
  const [cursorId, setCursorId] = useState<string | null>(null);

  // edito

  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法
  const [insertedImage, setInsertedImage] = useState<ImageElement[]>([]);
  // 编辑器内容
  const [html, setHtml] = useState(value); //最外层必须为p标签
  useEffect(() => {
    if (!!value) {
      const tmp = value.split(splitKey);
      if (tmp.length > 1) {
        setHtml(tmp.slice(1).join(splitKey));
      } else {
        setHtml(value);
      }
    }
  }, [value]);
  const addTokenToRul = (html: string) => {
    const regex = /src="([^"]+)/g;
    const token = iup.getUser().uCode;
    return html.replace(regex, function () {
      return `${arguments[0]}?token=${token}`;
    });
  };

  const onchangeEditor = (value) => {
    if (value !== '<p><br></p>') {
      !!onChange && onChange(`${cursorIdRef.current || ''}${splitKey}${value}`);
    } else {
      !!onChange && onChange('');
    }
    !onChange && setHtml(value);
  };
  // 工具栏配置
  // 转换图片链接
  const customParseImageSrc = (src: string): string => {
    if (src?.indexOf('http') !== 0) {
      return `http://${src}`;
    }
    return src;
  };
  const setInsertedImageFun = (imageNode: ImageElement): void => {
    // const urlList = imageNode?.map(i => )
    setInsertedImage([...insertedImage, imageNode]);
  };
  const user = util.getUser() || {};
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    MENU_CONF: {
      uploadImage: {
        server: '/iup-file/tripartite/rich-text-upload',
        // server: '/api/upload-image',
        fieldName: 'custom-field-name',
        allowedFileTypes: [],
        headers: {
          'User-Token': user.accessToken
        },
        meta: {
          otherKey: 'yyy'
        },
        onBeforeUpload(file: File) {
          console.log('file', file);
          return file;
        },
        // 单个文件上传成功之后
        onSuccess(file: File, res: any) {
          console.log(`${file.name} 上传成功`, res);
        },

        // 单个文件上传失败
        onFailed(file: File, res: any) {
          console.log(`${file.name} 上传失败`, res);
        },

        // 上传错误，或者触发 timeout 超时
        onError(file: File, err: any, res: any) {
          console.log(`${file.name} 上传出错`, err, res);
        },
        async customUpload(file: File, insertFn: InsertFnType) {
          // const chunkFile = File.prototype.slice.call(file, 1 * chunkSize, Math.min(partNum * chunkSize, size));
          const { name, size, type } = file;
          const chunkSize = 5242880;
          const currentChunkSize = chunkSize;
          const md5 = await getFileMd5(file);
          const params = {
            chunkNumber: 1,
            chunkSize: 5242880,
            currentChunkSize,
            totalChunks: 1,
            totalSize: size,
            fileName: name,
            md5,
            file,
            busiType: fileTypeCode || 'iupfile-type',
            cursorId: '',
            // todo 以下选填
            ctlgId: ''
          };
          if (!fileTypeCode) {
            iup.message('缺少fileTypeCode', 'warning');
            return;
          }
          const res = await richUploadFile(params as any);
          if (res.code !== 0) {
            return;
          }
          const userToken = iup.getUser().accessToken;
          const cursorId = res?.data?.cursorId;
          const url = res?.data?.previewUrl + '&User-Token=' + userToken;
          const href = '';
          const alt = 'test';
          cursorIdRef.current = cursorId;
          // setCursorId(cursorId)
          insertFn(url, alt, href);
        }
      },
      insertImage: {
        onInsertedImage(imageNode: ImageElement | null) {
          if (imageNode == null) return;

          const { src, alt, url, href } = imageNode;
          setInsertedImageFun(imageNode);

          console.log('setInsertedImageFun', imageNode);
        },
        parseImageSrc: customParseImageSrc // 也支持 async 函数
      }
    }
  };
  //   获取删除的图片及时调用接口输出
  useEffect(() => {
    const formImageList = editor?.getElemsByType('image');
  }, [editor?.getElemsByType('image'), insertedImage]);
  // 及时销毁 editor
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
    //   editor.getElemsByType('image')
  }, [editor]);
  return (
    <>
      <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{ borderBottom: '1px solid #ccc' }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={setEditor}
          onChange={(editor) => {
            onchangeEditor(editor.getHtml());
          }}
          mode="default"
          style={{ height: '500px', overflowY: 'hidden' }}
        />
      </div>
      {/* <div style={{ marginTop: '15px' }}>{html}</div> */}
    </>
  );
}

registerComponent({ HtmlEditor });
